package org.example.shejimoshi.create.danli;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipUtil {

    private static final String CHARSET = "UTF-8";

    public static byte[] compress(String input) throws UnsupportedEncodingException, IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gzipOutputStream.write(input.getBytes(CHARSET));
        gzipOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static String decompress(byte[] compressed) throws UnsupportedEncodingException, IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed);
        GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gzipInputStream.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        gzipInputStream.close();
        out.close();
        return out.toString(CHARSET);
    }
}
